package m.member.manage.action;

import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VuePageResult;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.VueTabResult;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.form.*;
import m.html.list.*;
import m.html.tab.TabItem;
import m.member.manage.model.MemberInfo;
import m.member.manage.model.MemberLevel;
import m.member.manage.service.MemberInfoService;
import m.member.order.action.MemberRechargeAction;
import m.member.order.action.OrderInfoAction;
import m.system.exception.MException;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;
import manage.action.StatusAction;
import manage.model.OrgGroupView;

import java.util.ArrayList;
import java.util.List;

@ActionMeta(name = "member/manage/memberInfo")
public class MemberInfoAction extends StatusAction {
    private MemberInfo model;
    public JSONMessage doSave() throws Exception {
        verifyAdminOperPower(getStatusPower());
        OrgGroupView org=getSessionOrgGroup();
        if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
            throw new MException(this.getClass(),"无店铺信息");
        String msg=getService(MemberInfoService.class).save(model,getSessionAdmin(),org.getDept());
        return new JSONMessage(0)
                .push("msg",msg);
    }
    public VueResult toEdit() throws Exception {
        verifyAdminOperPower(getStatusPower());
        if(ObjectUtil.isEmptyOid(model)){
            model=new MemberInfo();
        }else{
            model= ModelQueryList.getModel(model,"*");
        }
        ModelForm form=new ModelForm("编辑会员信息",2);
        form.addItem(
            FormInput.input("姓名","model.realName").setPlaceholder("请输入姓名"),
            FormInput.input("手机号","model.phoneNum").setPlaceholder("请输入手机号"),
            FormInput.date("生日","model.birthday").setPlaceholder("请选择生日"),
            FormInput.select("会员级别","model.level.oid","m.member.manage.model.MemberLevel").setPlaceholder("请选择会员级别"),
            FormInput.textarea("备注","model.remark").setSpan(2)
        )
        .addData("model",model)
        .addButton(
            FormButton.pri("保存","doSave")
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doSave",actionUrl("doSave"),"{model:this.model}")
                .success("backFlag")
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form);
//        以上写法可根据系统设置统一样式，下面写法是前端页面写法
//        return new VuePageResult("page/member/manage/editMemberInfo.js")
//                .addParam("model", model);
    }
    public VueResult toView() throws Exception {
        model= ModelQueryList.getModel(model,"*","level.*");
        if(!hasAdminOperPower(getStatusPower())){
            String pn = model.getPhoneNum();
            model.setPhoneNum(pn.substring(0, 3) + "****" + pn.substring(pn.length() - 4));
        }
        ModelForm form=new ModelForm("会员信息",2);
        form.addItem(
            FormHtml.ins("<a-tag :color=\"model.level.color\">{{model.level.name}}</a-tag>",
                    "{{model.realName}} （{{model.phoneNum}}）"),
            FormHtml.ins("余额","{{model.balance}} 元"),
            FormHtml.ins("生日","{{formatDate(model.birthday,'yyyy-MM-dd')}}"),
            FormHtml.ins("积分","{{model.point}} 分"),
            FormHtml.ins("备注","{{model.remark}}").setSpan(2)
        )
        .addData("model",model);
        LoadPage page=new LoadPage("memberData",actionUrl("toDataTab"),"{oid:this.model.oid}")
                .setMounted("this.memberData();");
        VueFormResult result=new VueFormResult();
        return result.addForm(form).addForm(page);
//        以上写法可根据系统设置统一样式，下面写法是前端页面写法
//        return new VuePageResult("page/member/manage/viewMemberInfo.js")
//                .addParam("model", model);
    }
    @RequestMeta(params = {"oid"})
    public VueResult toDataTab(String oid){
        VueTabResult tab=new VueTabResult("会员数据");
        tab.setSubTitle("{{tabs.names[indexKey]}}");
        tab.addItems(new TabItem("orderList","订单列表",
        actionUrl(OrderInfoAction.class,"memberOrderList")+"?params[member.oid]="+oid));
        tab.addItems(new TabItem("rechargeList","充值记录",
        actionUrl(MemberRechargeAction.class,"memberRechargeList")+"?params[member.oid]="+oid));
        return tab;
    }
    /*
     * 所有会员信息
     */
    public VueResult allList() throws Exception {
        OrgGroupView org=getSessionOrgGroup();
        if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
            throw new MException(this.getClass(),"无店铺信息");
        boolean power=hasAdminOperPower(getStatusPower());
        VueListResult result=getVueListResult("所有会员信息",MemberInfo.class,actionUrl("allList"));
        result.setFunction(true,false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addQueryFields("level.*","inputDept.oid");
        result.addCol(toTextColumn("会员级别", "level.oid", 100, true)
            .addElement(new ListElement("a-tag")
                .addAttr(":color","record.level.color")
                .addText("{{record.level.name}}")
            )
            .setDictType(MemberLevel.class)
            .setAlign(Align.CENTER)
        );
        result.addCol(toLinkColumn("姓名", "realName", 100, true,
            new ListEvent(actionUrl("toView"),EventType.MODAL,1000)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("手机号", "phoneNum", 100, true));
        result.addCol(toDateColumn("生日", "birthday", 100, true));
        result.addCol(toNumberColumn("已用金额", "useMoney", 100, true));
        result.addCol(toIntegerColumn("订单数", "orderNum", 100, true));
        result.addCol(toIntegerColumn("积分", "point", 100, true));
        result.addCol(toNumberColumn("余额", "balance", 100, true));
        result.addCol(toNumberColumn("冻结", "freeze", 100, true));
        result.addCol(toNumberColumn("实际金额", "realMoney", 100, true));
        result.addCol(toNumberColumn("赠送金额", "giveMoney", 100, true));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        result.addCol(toDateColumn("录入时间", "inputDate", 100, true));
        result.addCol(toTextColumn("录入人", "inputAdmin.realname", 100, true));
        result.addCol(toTextColumn("录入店铺", "inputDept.name", 100, true));
        //状态列，第一个参数 是否可操作
        result.addCol(toStatusColumn(power, true).setFixed(Align.RIGHT));
        if(power) {
            result.addCol(toSpaceColumn("操作", 100,
                ListElement.test("record.inputDept.oid=='"+org.getDept().getOid()+"'",
                    ListButton.modal("修改", ButtonType.PRIMARY, actionUrl("toEdit"), 700, SuccessMethod.REFRESH)
                        .addParam("model.oid", "oid")
                )
            ).setFixed(Align.RIGHT));
            result.addButton(ListButton.modal("新增", ButtonType.PRIMARY, actionUrl("toEdit"), 700, SuccessMethod.REFRESH));
        }
        //排序 result.addOrder
        //查询条件 result.addCondition
        return result;
    }

    /**
     * 选择会员信息
     */
    public VueResult selectList() throws Exception {
        String selected=getParamsValue("selected");
        VueListResult result=getVueListResult("选择会员信息",MemberInfo.class,actionUrl("selectList"));
        result.addCol(toIndexColumn());
        result.addQueryFields("oid","level.*");
        result.addCol(toTextColumn("会员级别", "level.oid", 100, true)
            .addElement(new ListElement("a-tag")
                .addAttr(":color","record.level.color")
                .addText("{{record.level.name}}")
            )
            .setDictType(MemberLevel.class)
            .setAlign(Align.CENTER)
        );
        result.addCol(toTextColumn("姓名", "realName", 100, true));
        result.addCol(toTextColumn("手机号", "phoneNum", 100, true)
            .setFieldExpression("concat(left(#{phoneNum},3),'****',right(#{phoneNum},4))"));
        result.addCol(toDateColumn("生日", "birthday", 100, true));
        result.addCol(toNumberColumn("余额", "balance", 100, true).setCount(ListCount.NONE));
        result.addCol(toNumberColumn("冻结", "freeze", 80, true).setCount(ListCount.NONE));
        result.addCol(toSpaceColumn("操作", 80,
            ListElement.test("record.oid!='"+selected+"'",
                ListButton.back("选择", ButtonType.PRIMARY).addParam("", "")
            )
        ).setFixed(Align.RIGHT));
        String searchText=getParamsValue("searchText");
        if(StringUtil.notSpace(searchText)) {
            String[] arr=searchText.split("\\s");
            List<QueryCondition> cons=new ArrayList<>();
            cons.addAll(QueryCondition.manyLike("realName",arr));
            cons.addAll(QueryCondition.manyLike("phoneNum",arr));
            result.addCondition(QueryCondition.or(cons.toArray(new QueryCondition[0])));
        }
        result.addSearch(ListSearch.custom("姓名或手机","searchText",SearchType.STR_EQ).setSpan(2));
        return result;
    }
    @Override
    public String[] getStatusPower() {
        return new String[]{"app_member_power"};
    }

    @Override
    public MemberInfo getModel() {
        return model;
    }

    public void setModel(MemberInfo model) {
        this.model = model;
    }
}
